<head>

    <meta charset="UTF-8"/>
    <title>测试上传文件</title>
    <script src="./lib/axios@0.24.0/dist/axios.min.js"></script>
</head>
<body>
<script>
    // fd=new FormData();
    // fd.append('desc','ddd');
    // fd.append('file','ss');
    // await axios.post('/Mongo/file/test',fd,{headers: {
    //         'Content-Type': 'multipart/form-data'
    //     }})
    function getById(id) {
        return document.getElementById(id);
    }

    /**
     *
     * @see <a href="https://blog.csdn.net/WuLex/article/details/84296934">input[type=file] 获取上传文件的内容</a>
     * @returns {Promise<void>}
     */
    async function submit() {
        console.log('--- submit ---');
        let file = getById('file').files[0];
        if (!file) {
            alert('请选择文件');
            return;
        }
        if (file.size === 0) {
            alert('禁止上传空文件');
            return;
        }
        let desc = getById('desc').value;
        if (!desc) {
            alert('请输入描述');
            return;
        }
        let base64 = await new Promise((resolve, reject) => {
            let reader = new FileReader();
            reader.onload = function (e) {
                resolve(reader.result);
            };
            reader.readAsDataURL(file);
        });
        let blob = await new Promise((resolve, reject) => {
            fetch(base64).then(res => res.blob().then(blob => resolve(blob)));
        });
        let fd = new FormData();
        fd.append("file", file);
        fd.append("desc", desc);
        let res = await axios.post('/Mongo/file/add', fd, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
        console.log('--- 上传结果 ---', res.data);
        window.upload = {
            file, desc, base64, blob, fd, res
        };
        console.log('--- upload ---', upload);


    }
</script>
<hr>
<div>
    <!--  https://blog.csdn.net/whd526/article/details/78178451  -->
    <!--  https://www.cnblogs.com/ooo0/p/7519828.html  -->
    <form method='POST'
          action="http://192.168.0.28:9068/Mongo/file/test"
          enctype='multipart/form-data' target="_self"
          onsubmit="return false"
          style="float: left"
    >
        <label>
            选择文件
            <input id="file" type='file' name='file'>
        </label>
        <label>
            文件描述
            <input id="desc" type='text' name='desc'>
        </label>
    </form>&nbsp;
    <button type="button" onclick="submit()">提交</button>
</div>
</body>
